package org.springblade.modules.notice.core.var;

import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author ysq
 * @Date 2024/11/27
 * @Description 变量解析器
 */
@Slf4j
@Component
public class VariableParse {

	@Resource
	private JdbcTemplate jdbcTemplate;

	public Map<String, String> parse(Long bizId, Set<String> varSqlSet) {
		Map<String, String> result = new HashMap<>(8);
		for (String varSql : varSqlSet) {
			try {
				Map<String, Object> map = jdbcTemplate.query(varSql, new Object[]{bizId}, new ResultSetExtractor<Map<String, Object>>() {
					@Override
					public Map<String, Object> extractData(ResultSet rs) throws SQLException, DataAccessException {
						if (rs.next()) {
							return rs2map(rs);
						} else {
							return Collections.emptyMap();
						}
					}

					private Map<String, Object> rs2map(ResultSet rs) throws SQLException {
						Map<String, Object> map = new HashMap<>();
						ResultSetMetaData metaData = rs.getMetaData();
						int columnCount = metaData.getColumnCount();
						for (int i = 1; i <= columnCount; i++) {
							String columnName = metaData.getColumnLabel(i);
							Object value = rs.getObject(i);
							if (value == null) {
								map.put(columnName, "-");
							} else {
								map.put(columnName, value);
							}
						}
						return map;
					}
				});

				map.forEach((k, v) -> result.put(k, String.valueOf(v)));
			} catch (DataAccessException e) {
				log.warn("解析变量sql执行异常:{}", varSql);
			}
		}
		return result;
	}
}
